package com.yueyang.sojourn.server.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.yueyang.sojourn.server.common.baymax.web.resolver.CatchAllExcetpionResolver;
import com.yueyang.sojourn.server.common.baymax.web.resolver.RestResultExceptionResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author Stephen.Shi
 * @version v1
 * @summary
 * @Copyright (c) 2019, yueyang Group All Rights Reserved.
 * @since 2020/2/2
 */
@Configuration
@Slf4j
public class MvcConfig implements WebMvcConfigurer {

    private boolean enableCatchAllLogExceptionTrace = true;
    @Value(value = "${mvc.exception.resolver.catchall.enabled:true}")
    private boolean enableCatchAllResolver = true;

    /**
     * REST断言是否打印异常堆栈
     */
    @Value(value = "${mvc.exception.resolver.restassert.logTrace:false}")
    private boolean enableRestAssertLogException = false;

    @Value(value = "${mvc.filter.instanceHeader.headerName:}")
    private String instanceHeaderName;

    /**
     * 配置FastJson为方式一
     *
     * @return
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        /*
         * 1、需要先定义一个convert转换消息的对象 2、添加fastJson的配置信息，比如：是否要格式化返回json数据 3、在convert中添加配置信息
         * 4、将convert添加到converters当中
         *
         */
        // 1、需要先定义一个·convert转换消息的对象；
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2、添加fastjson的配置信息，比如 是否要格式化返回json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);

//        fastJsonConfig.set
        // 3、在convert中添加配置信息.
        fastConverter.setFastJsonConfig(fastJsonConfig);
        // 4、将convert添加到converters当中.
        converters.add(0, fastConverter);
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 2允许任何头
        corsConfiguration.addAllowedMethod("*"); // 3允许任何方法（post、get等）
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        log.info("跨域1");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }


    /**
     * 配置跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        log.info("跨域2");
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("*");
    }

    @Override
    public void configureHandlerExceptionResolvers(
            List<HandlerExceptionResolver> exceptionResolvers) {
        // 只处理AbstractResultException所有子类异常
        exceptionResolvers.add(new RestResultExceptionResolver(this.enableRestAssertLogException));
        // 解析所有异常（除了 {@link AbstractResultException}），并输出json输出错误信息
        if (this.enableCatchAllResolver) {
            exceptionResolvers.add(new CatchAllExcetpionResolver(this.enableCatchAllLogExceptionTrace));
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 目前暂时采用这种方式。后面应改为权限方式。
        // 普通登录拦截
        registry.addInterceptor(loginInteceptor())
                .addPathPatterns("/api/wx/**")
                .excludePathPatterns("/sojourn/user/**");
        // 后台用户登录拦截
        registry.addInterceptor(adminLoginInteceptor())
                .addPathPatterns("/sojourn/**", "/share/**")
                .excludePathPatterns("/sojourn/user/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Bean
    public LoginInteceptor loginInteceptor() {
        return new LoginInteceptor();
    }

    @Bean
    public AdminLoginInteceptor adminLoginInteceptor() {
        return new AdminLoginInteceptor();
    }

}
